﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EventDemo
{
    public class PriceChangeEventArgs : EventArgs
    {
        public readonly decimal LastPrice;
        public readonly decimal NewPrice;
        public PriceChangeEventArgs(decimal lastPrice, decimal newPrice)
        {
            LastPrice = lastPrice;
            NewPrice = newPrice;
        }
    }
    public class Stock
    {
        string symbol;
        decimal price;
        public Stock(string symbol)
        {
            this.symbol = symbol;
        }
        public event EventHandler<PriceChangeEventArgs> PriceChanged;

        protected virtual void OnPriceChanged(PriceChangeEventArgs e)
        {
            //this指的是广播者Stock
            PriceChanged?.Invoke(this,e);
        }

        public decimal Price
        {
            get { return price; }
            set
            {
                if (price == value) return;
                decimal oldPrice = price;
                //和this类似有点像是个关键字
                price = value;
                //这个方法就会触发事件
                OnPriceChanged(new PriceChangeEventArgs(oldPrice,price));
            }
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Stock stock = new Stock("MSFT");
            stock.Price = 120;
            stock.PriceChanged += Stock_PriceChanged;
            stock.Price = 135;
        }

        private static void Stock_PriceChanged(object sender, PriceChangeEventArgs e)
        {
            //throw new NotImplementedException();
            if ((e.NewPrice - e.LastPrice)/e.LastPrice>0.1M)
            {
                Console.Write("Alert,10% stock price increase");
            }
            Console.Read();
        }
    }
}
